//
//  WKwebViewController.swift
//  BusinseeLifeBox
//
//  Created by admin on 2020/3/22.
//  Copyright © 2020 admin. All rights reserved.
//

import UIKit
import WebKit

class WKwebViewController: SupleViewController, WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate {

    @objc var url:NSString?
    static let processPool = WKProcessPool();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        confitUI()
        loadReuest()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        webview.configuration.userContentController .add(self, name: "getToken")
        webview.configuration.userContentController .add(self, name: "qrscan")
        webview.configuration.userContentController .add(self, name: "webdebug")
        webview.configuration.userContentController .add(self, name: "createTabCategory")
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        webview.configuration.userContentController .removeScriptMessageHandler(forName: "getToken")
        webview.configuration.userContentController .removeScriptMessageHandler(forName: "webdebug")
        webview.configuration.userContentController .removeScriptMessageHandler(forName: "qrscan")
        webview.configuration.userContentController .removeScriptMessageHandler(forName: "createTabCategory")
    }
    
    
    lazy var webview:WKWebView = {
        var config = WKWebViewConfiguration();
//        config.processPool = WKwebViewController.processPool;

        var webview = WKWebView(frame: .zero, configuration: config)
        webview.navigationDelegate = self
        webview.uiDelegate = self
        webview.scrollView.bounces = false;
        return webview
    }()
    
    
    
    lazy private var progressView: UIProgressView = {
        let progress = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: UIScreen.main.bounds.width, height: 2))
        progress.tintColor = UIColor.green
        progress.trackTintColor = UIColor.white
        return progress
    }()
    
    
    func confitUI() {
        view.addSubview(webview)
        view.addSubview(progressView)
        webview.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        webview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    func loadReuest() {
        if (url != nil) {
            //设置访问的ur
            let str = String.init(format: "%@",url!)
            var urlRequest = URLRequest(url: URL(string: str)!)
//            let tocken = "Bearer"+UserInfo.share().token
//            urlRequest.addValue("loginToken = \(tocken)", forHTTPHeaderField: "cookie")
            debugPrint(str)
            //加载请求
            webview.load(urlRequest)
        }
    }
 
}

extension WKwebViewController{
    
    override func leftNavBarTouchUp(inside sender: UIButton) {
        if webview.canGoBack {
//            webview.goBack()
            let jsaction = "goBackaction()"
            webview.evaluateJavaScript(jsaction, completionHandler: { (any, error) in
                if (error != nil) {
                    print(error.debugDescription)
                }else{
                    debugPrint("goBackaction end")
                }
            })
        }else{
            super.leftNavBarTouchUp(inside: sender)
        }
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        webview.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        progressView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(1)
        }
    }
}

extension WKwebViewController
{
    
    // 监听网页加载进度
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //设置进度条
        if keyPath == "estimatedProgress"{
            progressView.alpha = 1.0
            progressView.setProgress(Float(webview.estimatedProgress), animated: true)
            if webview.estimatedProgress >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                    self.progressView.alpha = 0
                }, completion: { (finish) in
                    self.progressView.setProgress(0.0, animated: false)
                })
            }
        }
            
            //重设标题
        else if keyPath == "title" {
            self.title = self.webview.title
        }
        
    }
    
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
        debugPrint("开始加载...")
    }
    
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        debugPrint("当内容开始返回...")
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        debugPrint( "页面加载完成...")
        /// 获取网页title
        self.title = self.webview.title
        UIView.animate(withDuration: 0.5) {
            self.progressView.isHidden = true
        }
    }
    
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        debugPrint( "页面加载失败...")
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 0.0
            self.progressView.isHidden = true
        }
        /// 弹出提示框点击确定返回
        let alertView = UIAlertController.init(title: "提示", message: "加载失败", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in
            _=self.navigationController?.popViewController(animated: true)
        }
        alertView.addAction(okAction)
        self.present(alertView, animated: true, completion: nil)
    }
    
    
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        debugPrint( "name=\(message.name) body=\(message.body)")
        if message.name == "getToken"{
            let body = message.body
            let tocken = "Bearer"+UserInfo.share().token
            let jsaction = "setTocken('\(tocken)','\(body)')"
            webview.evaluateJavaScript(jsaction, completionHandler: { (any, error) in
                if (error != nil) {
                    print(error.debugDescription)
                }else{
                    debugPrint("getToken end")
                }
            })
            
        }else if message.name == "createTabCategory"{
            //分类管理
            self.routepush("UGBox.TabCategoryViewController", param: nil)
        }else if message.name == "webdebug"{
            print("webdebug:\(message.body)")
        }else if message.name == "qrscan"{
            
            let qqScanViewController = QQScanViewController()
            qqScanViewController.fineshBlock = {(vc,result) in
                UIView.ug_starloading()
                Network.share().sellerReceipt(nil, code: nil, qrcode: result!) { (result, error) in
                    UIView.ug_stoploading()
                    if((error) != nil){
                        let nserror:NSError = error! as NSError
                        UIView.ug_msg(nserror.domain)
                        vc?.reStartDevice()
                    }else{
                        vc?.navigationController?.popViewController(animated: true)
                    }
                }
            }
            self.navigationController?.pushViewController(qqScanViewController, animated: true)
        }
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alertcontroller = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert)
        alertcontroller.addAction(UIAlertAction.init(title: "确认", style: .default) { (alert) in
            completionHandler();
        })
  
        self.present(alertcontroller, animated: true, completion: nil)
    }
    
}


